/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    public:
        ListNode* removeElements(ListNode* head, int val) {

            if (!head)
                return head;

            ListNode *p = head, *prev = NULL, *newhead = NULL, *q;

            while(p) {
                if (p->val == val) {
                    if (!newhead) {
                        q = p->next;
                        delete p;
                        p = q;
                    } else {
                        prev->next = p->next;
                        delete p;
                        p = prev->next;
                    }
                } else {
                    if (!newhead) {
                        newhead = p;
                    }
                    prev = p;
                    p = p->next;
                }
            }

            head = newhead;
            return head;
        }
};

